package class

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/mildware"
	"project/pkg/models"
	"project/pkg/validate"
	"strconv"
	"strings"
)

func (h CHandler) TeacherAddClass(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.TeacherAddClassReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Teacher:TeacherAddClass with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Teacher:TeacherAddClass with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//token
	id, _, _, err := mildware.GetCyrrentUserID(c)
	if err != nil {
		zap.L().Error("Teacher:mildware.GetCyrrentUserID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	req.TeacherId = id
	//判断名字重复
	exist, _, err := h.M.ClassCheckExistByName(req.Name)
	if err != nil {
		zap.L().Error("Teacher:ClassCheckExistByName err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		resp.SendCode(c, models.CodeUserExist)
		return
	}
	atoi, err := strconv.Atoi(req.Grade)
	if err != nil {
		zap.L().Error("Teacher:strconv.Atoi err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	classInfo := &models.ClassInfo{
		Grade:          atoi,
		Name:           req.Name,
		PeopleCount:    "0",
		NowPeopleCount: "0",
		LeaveCount:     "0",
		College:        req.College,
	}
	err = h.M.ClassUpdateInfoBuID(classInfo)
	if err != nil {
		zap.L().Error("Teacher:h.M.ClassUpdateInfoBuID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	//添加到teacher
	exist, info, err := h.M.ClassCheckExistByName(req.Name)
	if err != nil {
		zap.L().Error("Teacher:ClassCheckExistByName err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		teacher, teacherInfo, err := h.M.TeacherCheckExistByID(req.TeacherId)
		if err != nil {
			zap.L().Error("Teacher:TeacherCheckExistByID err", zap.Error(err))
			resp.SendServerBusy(c)
			return
		}
		if teacher {
			idStr := strconv.Itoa(int(info.ID))
			classList := strings.Split(teacherInfo.ClassList, "|")
			if classList[0] == "" {
				teacherInfo.ClassList = idStr
			} else {
				classList = append(classList, idStr)
				teacherInfo.ClassList = strings.Join(classList, "|")
			}
			//更新
			err := h.M.TeacherUpdateInfoBuID(teacherInfo)
			if err != nil {
				zap.L().Error("Teacher:TeacherUpdateInfoBuID err", zap.Error(err))
				resp.SendServerBusy(c)
				return
			}
		}
	}
	resp.SendSuccess(c)
}
